/*
 * ================================================================================变量定义区
 */
var showCount = 10; 		 // 定义每页显示条数
var currentPage = 1;		 // 全局变量，当前页
var treeNode; 				 // 组织机构树节点
var chooseIds = new Array(); // 选定的部门标识数组
var type=1;					//加入到这个组织机构	
/*
 * ================================================================================页面初始化函数
 */
$(function()
{
	// 加载组织机构树
	departmentTree();
	// 为部门中增加VDI
	$("#addVdi").click(function()
		{
			refreshCurrentPage();
		}
	);
	
	// 更新VDI
	$("#updateVdi").click(function()
		{
			updateVdi();
		}
	);
	
	// 查看VDI
	$("#detailVdi").click(function()
		{
			detailVdi();
		}
	);
	
	// 从部门中删除VDI
	$("#deleteVdi").click(function()
		{
			deleteVdis();
		}
	);
	

	// 取消提交部门变更
	$("#btnCancel").click(function()
		{
			showDepartmentUsersTab();
		}
	);

	$("#queryVdi").click(function()
		{
			queryVdiInfos(currentPage);
		}
	);
	
	$("#clearQueryCondition").click(function()
		{
			$.trim($("#loginName").val(""));
			$.trim($("#userName").val(""));
			$.trim($("#ip").val(""));
			$.trim($("#status").val("-1"));	
	    }
	);
	
	//回车键绑定事件
	document.onkeydown = function(event)
	{
	    var e = event || window.event || arguments.callee.caller.arguments[0];
	    
	     if(e && e.keyCode==13) // enter 键
	     {
	         //从第一页开始，查询数据
	    	 queryVdiInfos(currentPage);
	     }
	};
	
}
);

/*
 * ================================================================================函数定义区
 * 
 */

/**
 * 更新vdi
 */
function updateVdi()
{
	if (chooseIds.length==1) 
	{
		var id;
		
		for( var i = 0; i < chooseIds.length; i++ )
		{
			 id = $("#" + chooseIds[i] ).children("td").first().text();
		}
		
		$.trim($("#vdiId").val(id));
		$("#submitcurrentpage").submit();
		chooseIds = new Array();
		$.trim($("#loginName").val(""));
		$.trim($("#userName").val(""));
		$.trim($("#ip").val(""));
		$.trim($("#status").val("-1"));	
		$("#" + treeNode.tId + "_a").trigger("click");
		
	}else if(chooseIds.length>1){
		
		openAlert("最多选择一条VDI！"); 
		
	}else{
		
		openAlert("至少选择一条VDI！"); 
		
	}
	
}

/**
 * 加载树和树的点击事件
 */
function departmentTree()
{
	var setting = 
	{
		data: 
		{
			key: 
			{
				title:"titleTip"
			},
			simpleData: 
			{
				enable: true
			}
		},
		callback: 
		{
			onClick: showDepartmentVdis
		}
		};

	var zNodes = '[';
	
	$.ajax(
	{
		type: 'POST',
        url: BASE_PATH +'/vdiManagement/queryDepartments.do',
        dataType:"json",
        data:
        {
        },
        success:function(data,textStatus)
        {
        	for( var i = 0; i < data.length; i++ )
        	{
        		zNodes += '{id:"' + convertSpecialChar(data[i].deptId) + '",';
        		zNodes += 'pId:"' + convertSpecialChar(data[i].parentId) + '",';
        		zNodes += 'name:"' + convertSpecialChar( data[i].deptName ) + '",';
        		zNodes += 'titleTip:"' + convertSpecialChar( data[i].deptName ) + '",';
        		if( data[i].deptDesc == null )
        		{
            		zNodes += 'deptDesc:"",';
        		} 
        		else 
        		{
            		zNodes += 'deptDesc:"' + convertSpecialChar( data[i].deptDesc ) + '",';
        		}
        		zNodes += 'isLeaf:"' + data[i].isLeaf + '",';
        		zNodes += 'open:true}';
        		
        		if( i != (data.length - 1) )
        		{
        			zNodes += ',';
        		}
        	}
        	zNodes += ']';
    		// 加载树
    		$.fn.zTree.init($("#departmentTree"), setting, eval(zNodes));

    		$("#departmentTree_1_a").trigger("click");
        },
		error:function(e)
		{
			openAlert("加载数据错误！"); 
			return;
		}
	}
	);
}

/**
 * 点击树节点展示树下所有VDI信息
 * 
 * @param event
 * @param treeId
 * @param treeNode	
 * @param clickFlag
 */
function showDepartmentVdis(event, treeId, tempTreeNode, clickFlag) 
{
	if( treeNode != null && treeNode.id != tempTreeNode.id )
	{
		// 切换节点 ，都从第一页开始
		currentPage = 1;
	}
	// 全局变量赋予树节点ID
	treeNode = tempTreeNode;
	
	//初始化列表，取第一页数据
	getDataList(currentPage);
	
	// 列表和新建（或修改）相互切换
	showDepartmentUsersTab();
}			

/**
 * 获取列表数据
 * @param pageIndex 请求的页码
 */
function getDataList(pageIndex)
{
	chooseIds = new Array();
	$.ajax(
	{
		type: 'POST',
		async: false,
        url: BASE_PATH +'/vdiManagement/queryVdiInfosInDepartment.do',
        dataType:"json",
        data:
        {
        	"showCount"		                    :showCount,
        	"currentPage"	                    :pageIndex,
        	"deptId"		                    :treeNode.id,
        	"type"								:type,
        	"query_condition_field_list"		:"deptId,type"
        },
        cache:false,
        success:function(data,textStatus)
        {	
        	var html = "";        	
        	var pageData = data;
        	var totalResult = pageData.queryParam.totalResult;
        	if(pageData.queryResult != null)
        	{
        		// 获取分页数据，构造列表展示
	        	$.each(pageData.queryResult,function(i,n)
		        	{
		        		html += '<tr onclick="chooseRow(this,false);" id="tr_index_'+i+'" class="chooseUser" data-status='+ switcHtml(n.status)+'>';
		        		html += '<td style="display:none;" title='+switcHtml(n.id) +'><input type="hidden"  value="'+ switcHtml(n.id) +'"/>'+ switcHtml(n.id) +'</td>';
		        		html += '<td title='+switcHtml(n.loginName) +'><input type="hidden" value="'+ switcHtml(n.loginName) +'"/>'+ switcHtml(n.loginName) +'</td>';
		        		html += '<td style="text-align:left;" title='+ switcHtml(n.ip) +'>'+ switcHtml(n.ip) +'</td>';
		        		html += '<td style="text-align:left;" width="200" title='+ switcHtml(n.computerName) +'>'+ switcHtml(n.computerName) +'</td>';
		        		html += '<td style="text-align:right;" title='+ n.syscount +'>'+ n.syscount +'</td>';
		        		html += '<td style="text-align:left;" title='+ switcHtml(n.users) +'>'+ switcHtml(n.users) +'</td>';
		        		html += '<td style="text-align:center;" title='+ switcHtml(n.status) +'>'+ switcHtml(n.status) +'</td>';
		        		html += '<td style="width: 1px;"></td>';
		        		html += '</tr>';
		        	}
	        	);  
        	} 
        	else
        	{
        		html = '<tr><td colspan="2">No items.</td></tr>';
        	}
        	$('#tBodyList').html(html);
        	
        	currentPage = pageIndex;
    		if(totalResult == 0)
    		{
    			$('#tBodyList').html('<tr><td style="text-align:center;">No items.</td></tr>');
    			
    			// 没有记录的时候，隐藏分页插件
    			$("#pagination").hide();
    		} 
    		else 
    		{
    			// 创建分页
    			$("#pagination").show();
    			$("#pagination").pagination(totalResult, 
    			{
    				num_edge_entries: 1, //边缘页数
    				num_display_entries: 3, //主体页数
    				current_page:currentPage,
    				callback: getDataList,
    				items_per_page:showCount //每页显示1项
    			}
    			);
    		};
        },
		error:function(e)
		{
			openAlert("加载数据错误！"); 
			return;
		}
	}
	);
} 



/**
 * 展示组织机构列表
 */
function showDepartmentUsersTab()
{
	$("#userListTable").show();
	$("#deptName").removeClass("validate-input-error");
	$("div[for='deptName']").remove();
	$("#groupInfoDiv").hide();
}

/**
 * 选择一行
 */
function chooseRow(o) 
{
	var id = $(o).attr("id");
	var flag = false;
	var index = null;
	if (chooseIds.length > 0) 
	{
		for (var i = 0; i < chooseIds.length; i++) 
		{
			if (chooseIds[i] == id) 
			{
				index = i;
				flag = true;
				break;
			}
		}
	}
	
	if (flag) 
	{
		$(o).removeClass("list_choosedRow");
		chooseIds = deleteArrayByIndex(index, chooseIds);
	} 
	else 
	{
		$(o).addClass("list_choosedRow");
		chooseIds.push(id);
	}
}

/**
 * 查询VDI
 */
function queryVdiInfos(pageIndex)
{
	chooseIds = new Array();
	var loginName = $.trim($("#loginName").val());
	var userName = $.trim($("#userName").val());
	var ip = $.trim($("#ip").val());
	var status = $.trim($("#status").val());
	$.ajax({
		type: 'POST',
		async: false,
        url: BASE_PATH +'/vdiManagement/queryVdiInfos.do',
        dataType:"json",
        data:
        {
        	"showCount"		                    :showCount,
        	"currentPage"	                    :pageIndex,
        	"deptId"		                    :treeNode.id,
        	"loginName"							:loginName,
        	"userName"							:userName,
        	"ip"								:ip,
        	"status"							:status,
        	"type"								:type,
        	"query_condition_field_list"		:"loginName,deptId,userName,ip,status,type"
        },
        cache:false,
		success : function(data,textStatus) {
			var html = "";        	
        	var pageData = data;
        	var totalResult = pageData.queryParam.totalResult;
        	if(pageData.queryResult != null)
        	{
        		// 获取分页数据，构造列表展示
	        	$.each(pageData.queryResult,function(i,n)
	        	{
	        		html += '<tr onclick="chooseRow(this,false);" id="tr_index_'+i+'" class="chooseUser" data-status='+ switcHtml(n.status) +'>';
	        		html += '<td style="display:none;" title='+switcHtml(n.id) +'><input type="hidden"  value="'+ switcHtml(n.id) +'"/>'+ switcHtml(n.id) +'</td>';
	        		html += '<td title='+switcHtml(n.loginName) +'><input type="hidden" value="'+ switcHtml(n.loginName) +'"/>'+ switcHtml(n.loginName) +'</td>';
	        		html += '<td style="text-align:left;" title='+ switcHtml(n.ip) +'>'+ switcHtml(n.ip) +'</td>';
	           		html += '<td style="text-align:left;" width="200" title='+ switcHtml(n.computerName) +'>'+ switcHtml(n.computerName) +'</td>';
	        		html += '<td style="text-align:right;" title='+ n.syscount +'>'+ n.syscount +'</td>';
	        		html += '<td style="text-align:left;" title='+ switcHtml(n.users) +'>'+ switcHtml(n.users) +'</td>';
	        		html += '<td style="text-align:center;" title='+ switcHtml(n.status) +'>'+ switcHtml(n.status) +'</td>';
	        		html += '<td style="width: 1px;"></td>';
	        		html += '</tr>';
	        	}
	        	);  
        	} 
        	else
        	{
        		html = '<tr><td colspan="2">No items.</td></tr>';
        	}
        	$('#tBodyList').html(html);
        	
        	currentPage = pageIndex;
    		if(totalResult == 0)
    		{
    			$('#tBodyList').html('<tr><td style="text-align:center;">No items.</td></tr>');
    			// 没有记录的时候，隐藏分页插件
    			$("#pagination").hide();
    		} 
    		else 
    		{
    			// 创建分页
    			$("#pagination").show();
    			$("#pagination").pagination(totalResult, 
    			{
    				num_edge_entries: 1, //边缘页数
    				num_display_entries: 3, //主体页数
    				current_page:currentPage,
    				callback: getDataList,
    				items_per_page:showCount //每页显示1项
    			}
    			);
    		};
		},
		error:function(e)
		{
			openAlert("加载数据错误！"); 
			return;
		}
	});
}

/**
 * 删除VDIS
 */
function deleteVdis() 
{
	if (chooseIds.length > 0) 
	{
		var ids = new Array();
		var flag = false;
		for( var i = 0; i < chooseIds.length; i++ )
		{
			var id = $("#" + chooseIds[i] ).children("td").first().text();
			if($("#" + chooseIds[i] ).data("status")=="使用中"){
				flag = true;
				break;
				
			}else{
				// 拼接需要移除的VDI集合
				ids.push( encodeURIComponent(id) );
			}
		}
		if(flag){
			openAlert('使用中的VDI不能删除');
			return;
		}
		
		var tempar = new Array();
		tempar.push(1);
		openConfirm("确认从组织中移除选定的VDI吗？", this, function()
		{
			$.ajax(
			{
				type: 'POST',
				url : BASE_PATH + "/vdiManagement/removeVdiFromDepartment.do?ids=" + encodeURIComponent(ids),
		        dataType:"json",
		        data:
		        {
		        },
				success : function( data ) 
				{
					if( data == 'success' )
					{
						// 点击树节点
						$("#" + treeNode.tId + "_a").trigger("click");
						openAlert('移除VDI成功',function()
							{
								chooseIds = new Array();
							}
						);
					} 
					else
					{
						openAlert('移除VDI失败');
					}
				}
			}
			);
		}
		, tempar);
	} 
	else 
	{
		openAlert("请至少选择一个VDI！"); 
	}
}

/**
 * 新增VDI时跳转页面
 */
function refreshCurrentPage()
{
	$("#refreshcurrentpage").submit();
}

/**
 * 查看VDI详细信息
 */
function detailVdi(){
	
	if (chooseIds.length==1) 
	{
		var id;
		for( var i = 0; i < chooseIds.length; i++ )
		{
			 id = $("#" + chooseIds[i] ).children("td").first().text();
			
		}
		$.trim($("#vdiID").val(id));
		$("#detialVdipage").submit();
		chooseIds = new Array();
		$("#" + treeNode.tId + "_a").trigger("click");
	}else if(chooseIds.length>1){
		openAlert("最多选择一条VDI！"); 
	}else{
		openAlert("至少选择一条VDI！");
	}
	
}
